package org.com.lcuiot.handler;


import org.com.lcuiot.database.dto.Result;
import org.com.lcuiot.security.GetTokenInfo;

import org.com.lcuiot.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;



/**
 * 产品信息处理器
 *
 * @author gaoge
 * @since 2022/10/27 15:29
 */
@RestController
public class ProductHandler extends AbstractHandler{
    private final ProductService productService;

    @Autowired
    public ProductHandler(ProductService productService) {
        this.productService = productService;
    }


    @Bean
    public RouterFunction<ServerResponse> productRouter() {
        return route()
                .GET("/all_product", this::selectAllProductsHandler)
                .GET("/query_product/{productId}", this::selectByProductIdHandler)
                .build();
    }

    /**
     * 根据机构ID查询产品列表
     *
     * @param request 请求参数
     * @return Mono<ServerResponse>
     */
    public Mono<ServerResponse> selectAllProductsHandler(ServerRequest request) {
        return GetTokenInfo.getAuthentication().flatMap(auth ->{
               Result<Object> result =  productService.selectProductByOrganizationId(auth.getOrganizationId());
               return resolveResult(result); }
         );

    }

    /**
     * 根据产品id查询产品信息
     *
     * @param request 请求参数
     * @return Mono<ServerResponse>
     */
    public Mono<ServerResponse> selectByProductIdHandler(ServerRequest request) {
        String productId = request.pathVariable("productId");
        Result<Object> result = productService.selectByProductId(productId);
        return resolveResult(result);
    }


}
